package com.aaa.overlayviewdemo;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

/**
 * create by water.yuan
 * on 2020-09-27
 */
public class MyViewManager {

    private static volatile MyViewGroup sMyViewGroup;

    public static void showOverlayViewWithRequest(Context context) {
        if (Build.VERSION.SDK_INT >= 23 && !Settings.canDrawOverlays(context)) {
            Intent intent = new Intent(context, RequestOverlayActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            showOverlayView(context);
        }
    }

    public static void showOverlayView(Context context) {
        if (sMyViewGroup == null) {
            synchronized (MyViewManager.class) {
                if (sMyViewGroup == null) {
                    sMyViewGroup = new MyViewGroup(context).setCallback(view -> {
                        sMyViewGroup.setVisibility(View.GONE);
                    });
                    addViewToWindow(context, sMyViewGroup);
                }
            }
        }
        if (sMyViewGroup.getVisibility() != View.VISIBLE) {
            sMyViewGroup.setVisibility(View.VISIBLE);
        }
    }

    private static void addViewToWindow(Context context, View view) {
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= 26) { // Android 8.0 添加TYPE_APPLICATION_OVERLAY，废弃TYPE_PHONE
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        params.format = PixelFormat.RGBA_8888;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.START | Gravity.TOP;
        params.x = 100;
        params.y = 0; // todo：负值与0等效，0从状态栏下边开始

        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(view, params);
    }
}
